//
//  PaperDataManager.m
//  DoingPaper
//
//  Created by zhuxuhong on 16/7/26.
//  Copyright © 2016年 zhuxuhong. All rights reserved.
//

#import "PaperDataManager.h"

@implementation PaperDataManager
{
    NSString *papersPath;
    NSString *zipsPath;
}

-(instancetype)init{
    if (self = [super init]) {
        [self initialCreateFolder];
    }
    return self;
}

-(void)initialCreateFolder{
    papersPath = [NSHomeDirectory() stringByAppendingString:@"/Documents/papers"];
    zipsPath = [NSHomeDirectory() stringByAppendingString:@"/Documents/zips"];
    [self createDirectoryAtPath:papersPath];
    [self createDirectoryAtPath:zipsPath];
}

+(PaperDataManager*)sharedManager{
    static PaperDataManager* manager = nil;
    static dispatch_once_t token;
    dispatch_once(&token, ^{
        manager = [PaperDataManager new];
        [manager initialCreateFolder];
    });
    return manager;
}

/**
 *  网络连接
 */
-(BOOL)checkNetworkConnection{
    return true;
}

#pragma mark main method
// 加载试卷
-(PaperModel *)loadPaperWithPaperId:(NSString *)paperId{
    NSString *path = [self paperPlistPathWithId:paperId];
    if ([self fileExists:path]) {
        NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];
        PaperModel *paper = [[PaperModel alloc]initWithDict: dict[@"root"]];
        paper.paperId = paperId;
        
        // 试题归类，分拣【子题】
        NSMutableArray *subs = [NSMutableArray new];
        for (PaperItem *item in paper.items) {
            // 分拣
            for (PaperQuestion *q in item.questions) {
                if (![q.parentid isEqualToString:@"0"]) {
                    q.questionNum = subs.count + 1;
                    [subs addObject:q];
                }
                
                // 是判断题
                if (q.qtype && [q.qtype isEqualToString:@"3"]) {
                    [q.options addObject: [[PaperQuestionOption alloc]initWithDict:@{@"text":@"正确"}]];
                    [q.options addObject: [[PaperQuestionOption alloc]initWithDict:@{@"text":@"错误"}]];
                }
            }
            // 归类
            for (PaperQuestion *q in item.questions) {
                for (PaperQuestion *sub in subs) {
                    if ([sub.parentid isEqualToString:q.tqId]) {
                        [q.subQuestions addObject:sub];
                    }
                }
            }
            [item.questions removeObjectsInArray:subs];
            [subs removeAllObjects];
        }
        
        return paper;
    }
    return nil;
}

// 外部接口，实现用户已提交试题和答案的绑定
-(void)scanPaperWithSubmitedPaper:(PaperModel*)paper
                             Param:(PaperParam *)param
                           succeed:(PaperRequestSucceedBlock)succeedBlock
                          finished:(PaperRequestFinishedBlock)finishedBlock
                            failed:(PaperRequestFailedBlock)failedBlock{
    NSString *path = [self userAnswerJsonPathWithId: paper.paperId];
    if ([self fileExists:path]) {
        [self parseUserAnswerAndScoreRateFromPath:path paper:paper succeed:succeedBlock finished:finishedBlock];
    }
//    else{
//        [self getUserAnswerWithPaper:paper Param:param succeed:succeedBlock finished:finishedBlock failed:failedBlock];
//    }
}

// 试卷
-(NSString*)paperFolderPathWithId: (NSString*)paperId{
    return [NSString stringWithFormat:@"%@/paper_%@/",papersPath,paperId];
}
// 试卷images
-(NSString*)paperImagesPathWithId: (NSString*)paperId{
    return [NSString stringWithFormat:@"%@images/",[self paperFolderPathWithId: paperId]];
}
// 试卷plist
-(NSString*)paperPlistPathWithId: (NSString*)paperId{
    return [NSString stringWithFormat:@"%@paper.plist",[self paperFolderPathWithId: paperId]];
}
// 用户答案json
-(NSString*)userAnswerJsonPathWithId: (NSString*)paperId{
    return [NSString stringWithFormat:@"%@answer.json",[self paperFolderPathWithId: paperId]];
}
// 用户答案zip
-(NSString*)userAnswerZipPathWithId: (NSString*)paperId{
    return [NSString stringWithFormat:@"%@answer.zip",[self paperFolderPathWithId: paperId]];
}
// 收藏试题json
-(NSString*)collectedQuestionJsonPathWithId: (NSString*)paperId{
    return [NSString stringWithFormat:@"%@question.json",[self paperFolderPathWithId: paperId]];
}
// 收藏试题zip
-(NSString*)collectedQuestionZipPathWithId: (NSString*)paperId{
    return [NSString stringWithFormat:@"%@question.zip",[self paperFolderPathWithId: paperId]];
}

// 添加评语+打分
-(void)teacherSendCommentWithPaper:(PaperModel *)paper
                       PaperParam:(PaperParam *)param
                          succeed:(PaperRequestSucceedBlock)succeedBlock
                         finished:(PaperRequestFinishedBlock)finishedBlock
                           failed:(PaperRequestFailedBlock)failedBlock{
    
//    [self submitPaperOrSendCommentWithPaper:paper PaperParam:param succeed:succeedBlock finished:finishedBlock failed:failedBlock];
}

// 交卷
-(void)submitPaperAnwserWithPaper:(PaperModel *)paper
                       PaperParam:(PaperParam *)param
                          succeed:(PaperRequestSucceedBlock)succeedBlock
                         finished:(PaperRequestFinishedBlock)finishedBlock
                           failed:(PaperRequestFailedBlock)failedBlock{
    
//    [self submitPaperWithPaper:paper PaperParam:param succeed:succeedBlock finished:finishedBlock failed:failedBlock];
}

// 或得用户答案
-(void)getUserAnswerWithPaper:(PaperModel*)paper
                          Param:(PaperParam *)param
                        succeed:(PaperRequestSucceedBlock)succeedBlock
                       finished:(PaperRequestFinishedBlock)finishedBlock
                         failed:(PaperRequestFailedBlock)failedBlock{

//    NSString *base = [self paperBaseUrl];//@"http://172.19.42.53:7777/tqmsapp/app/homework/api";
    NSString *url = @"";//[NSString stringWithFormat:@"%@/getUserExamResultNew.do?userId=%@&uuid=%@",base, param.user_id,param.uuid];
    NSLog(@"load answer url: %@",url);
    
    NSURL *URL = [NSURL URLWithString: url];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    __weak __typeof(self) weakSelf = self;
    NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        NSURL *path = [NSURL fileURLWithPath: zipsPath];
        return [path URLByAppendingPathComponent:[response suggestedFilename]];
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        if (error) {
            failedBlock(error);
        }
        else{
            [weakSelf parseAnswerZipWithFilePath:filePath.path
                                           paper:paper Param:param
                                         succeed:succeedBlock
                                        finished:finishedBlock
                                          failed:failedBlock];
        }
    }];
    [task resume];
}

// 解压答案
-(void)parseAnswerZipWithFilePath:(NSString*)filePath
                          paper:(PaperModel*)paper
                            Param:(PaperParam*)param
                         succeed:(PaperRequestSucceedBlock)succeedBlock
                        finished:(PaperRequestFinishedBlock)finishedBlock
                          failed:(PaperRequestFailedBlock)failedBlock{
    __weak __typeof(self) weakSelf = self;
    [SSZipArchive unzipFileAtPath:filePath toDestination: [self paperFolderPathWithId:paper.paperId] overwrite:true password:nil progressHandler:^(NSString * _Nonnull entry, unz_file_info zipInfo, long entryNumber, long total) {
    } completionHandler:^(NSString * _Nonnull path, BOOL succeeded, NSError * _Nonnull error) {
        if (error) {
            failedBlock(error);
        }
        else{
            path = [weakSelf userAnswerJsonPathWithId: paper.paperId];
            [weakSelf parseUserAnswerAndScoreRateFromPath:path
                                                   paper:paper
                                                 succeed:succeedBlock
                                                 finished:finishedBlock];
        }
    }];
}

// 数据深层次解析
-(void)parseUserAnswerAndScoreRateFromPath:(NSString*)path
                                        paper:(PaperModel*)paper
                                   succeed:(PaperRequestSucceedBlock)succeedBlock
                                  finished:(PaperRequestFinishedBlock)finishedBlock
{
    NSData *data = [NSData dataWithContentsOfFile:path];
    if (!data) {
        NSLog(@"read answer.json to data is failed");
        return;
    }
    NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data  options:NSJSONReadingMutableContainers error:nil];
    for (NSDictionary *dict in jsonDict[@"qstData"])
    {
        NSString *userAnswer = dict[@"userAnswer"];
        NSString *score = dict[@"userScoreRate"];
        NSString *qId = dict[@"qstId"];
        
        NSLog(@"%@",userAnswer);
        for (PaperItem *item in paper.items) {
            for (PaperQuestion *q in item.questions) {
                if ([q.qstId isEqualToString:qId]) {
                    q.userAnswer = userAnswer;
                    q.markedScore = score;
                    break;
                }
            }
        }
        
    } //outside for loop end
    
    finishedBlock();
    succeedBlock();
}

#pragma mark - 下载试题zip
-(void)getPaperWithParam:(PaperParam *)param
                      succeed:(DownloadPaperSucceedBlock)succeedBlock
                     finished:(PaperRequestFinishedBlock)finishedBlock
                       failed:(PaperRequestFailedBlock)failedBlock{
    
    [self createDirectoryAtPath: [self paperFolderPathWithId: param.paperId]]; //folder
    [self createDirectoryAtPath: [self paperImagesPathWithId: param.paperId]]; //imags
    
    NSString *paperUrl = [NSString stringWithFormat:@"%@/getPaperData.do?paperId=%@",[self paperBaseUrl], param.paperId];
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    
    NSURL *URL = [NSURL URLWithString: paperUrl];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    
    NSLog(@"download paper url: %@",URL);
    __weak __typeof(self) weakSelf = self;
    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        NSURL *path = [NSURL fileURLWithPath: zipsPath];
        return [path URLByAppendingPathComponent:[response suggestedFilename]];
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
        if (error) {
            failedBlock([NSError errorWithDomain:@"试卷下载失败" code:404 userInfo:nil]);
        }
        else{
            /*NSString *testPaperPath = [[NSBundle mainBundle] pathForResource:@"paper.XML" ofType:nil];
            NSData *data = [NSData dataWithContentsOfFile: testPaperPath];
            NSError *error = nil;
            NSDictionary *dict = [XMLReader dictionaryForXMLData:data
                                                         options:XMLReaderOptionsProcessNamespaces
                                                           error:&error];
            NSString *path = [self paperPlistPathWithId: param.paperId];
            [dict writeToFile: path atomically:true];
            PaperModel *paper = [self loadPaperWithPaperId: param.paperId];
            param.paperName = paper.title;
            
            succeedBlock(paper);
            
            return;*/
            // 解析数据
            [weakSelf parsePaperZipWithFilePath:filePath.path//filePath.path
                                          Param:param
                                        succeed:succeedBlock
                                       finished:finishedBlock
                                         failed:failedBlock];
        }
    }];
    [downloadTask resume];
}

// 解压并解析试题
-(void)parsePaperZipWithFilePath:(NSString*)filePath
                           Param:(PaperParam*)param
                         succeed:(DownloadPaperSucceedBlock)succeedBlock
                        finished:(PaperRequestFinishedBlock)finishedBlock
                          failed:(PaperRequestFailedBlock)failedBlock{
    
    [SSZipArchive unzipFileAtPath: filePath toDestination: zipsPath progressHandler:^(NSString * _Nonnull entry, unz_file_info zipInfo, long entryNumber, long total) {
    } completionHandler:^(NSString * _Nonnull path, BOOL succeeded, NSError * _Nonnull error) {
        if (error) {
            failedBlock([NSError errorWithDomain:@"试卷解压失败" code:404 userInfo:nil]);
        }
        else{
            NSData *data = [NSData dataWithContentsOfFile: [zipsPath stringByAppendingString:@"/paper.XML"]];
            NSError *error = nil;
            NSDictionary *dict = [XMLReader dictionaryForXMLData:data
                                                         options:XMLReaderOptionsProcessNamespaces
                                                           error:&error];
            NSString *path = [self paperPlistPathWithId: param.paperId];
            if (dict && [dict writeToFile: path atomically:true]) {
                PaperModel *paper = [self loadPaperWithPaperId: param.paperId];
                param.paperName = paper.title;
                NSLog(@"paper saved to: %@", path);
                
                // 移动image文件夹到 papers/paper_xxx/
                NSString *toPath = [self paperImagesPathWithId: param.paperId];
                NSString *imagePath = [zipsPath stringByAppendingString:@"/image/"];
                [self moveFilesAtDirectory:imagePath toPath:toPath];
                
                // 删除zip包和其他解压文件
                NSFileManager *fm = [NSFileManager defaultManager];
                if ([fm removeItemAtPath:zipsPath error:nil]) {
                    NSLog(@"已清空试题解压缓存目录");
                    [self createDirectoryAtPath:zipsPath];
                }
                
                succeedBlock(paper);
            }
        }
        finishedBlock();
    }];
}

#pragma mark - 交卷
-(void)submitPaperNewWithPaper: (PaperModel *)paper
                              PaperParam:(PaperParam *)param
                                 succeed:(PaperRequestSucceedBlock)succeedBlock
                                  failed:(PaperRequestFailedBlock)failedBlock{
    
    /*
     paperId://试卷id
         userId://学生id
         userTrueName://学生姓名
         userLoginName：
         schoolUserId://学校ＩＤ
         schoolLoginName:    schoolTrueName://学校名称
         EXAM_FIRISTTIME:"2016-08-29 16:00:00.000"//开始答题时间
         EXAM_FINISHTIME:"2016-08-29 17:30:00.000"//答题完成时间
     */
    NSDictionary *paramDict =
    @{
      @"paperId": param.paperId,
      @"userId": param.userId,
      @"userTrueName": @"",
      @"userLoginName": param.loginName,
      @"schoolUserId": @"0",
      @"schoolLoginName": @"",
      @"schoolTrueName": @"",
      @"EXAM_FIRISTTIME": paper.startTime,
      @"EXAM_FINISHTIME": paper.finishTime,
      @"qstData": [self userAnswersDataOfPaper:paper],
      @"EXAM_SCORE": @(paper.gotScore)
    };
    
    NSString *jsonString = [self jsonStringFromJsonObject:paramDict];
//    jsonString = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"test.json" ofType:nil] encoding:NSUTF8StringEncoding error:nil];
    
    NSString *url = [NSString stringWithFormat:@"%@/getStudentResult.do",[self paperBaseUrl]];
//    NSLog(@"url: %@\n parameters: %@",url, jsonString);
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = nil;
    [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:url parameters:paramDict error:nil];

    NSError *defaultError = [NSError errorWithDomain:@"交卷失败" code:404 userInfo:nil];
    [manager POST:url parameters:@{@"jsonData": jsonString} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
     
         // {"message":"交卷成功","status":"1"}
        NSLog(@"task: %@ \n response: %@", task, responseObject);
        if ([responseObject[@"status"] boolValue]) {
            // 把做题记录保存到本地.json
            NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:false];
            BOOL writed = [data writeToFile:[self userAnswerJsonPathWithId:paper.paperId] atomically:true];
            if (!writed) {
                failedBlock(defaultError);
                return;
            }
            [self savePaperScoreToServerWithPaper:paper paperParam:param succeed:succeedBlock failed:failedBlock];
        }
        else{
            failedBlock(defaultError);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (error) {
            NSLog(@"failed: %@",error.localizedDescription);
            failedBlock(error);
        }
    }];
}

// paper model to json and zip it
-(NSString *)jsonPathOfUserAnswersForParamDict: (NSDictionary*)param{
    NSString *jsonStr = [self jsonStringFromJsonObject: param];
    NSData *data = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
    NSString *jsonPath = [self userAnswerJsonPathWithId: param[@"jsonData"][@"paperId"]];
    BOOL writed = [data writeToFile:jsonPath  atomically:true];
    if (writed) {
        // zip
        NSLog(@"answer json path: %@",jsonPath);
        return jsonPath;
    }
    return nil;
}

-(NSArray*)userAnswersDataOfPaper: (PaperModel*)paper{
    NSMutableArray *answers = [NSMutableArray new];
    for (PaperItem *item in paper.items) {
        for (PaperQuestion *q in item.questions) {
            NSMutableDictionary *dict = [NSMutableDictionary new];
            dict[@"standardAnswer"] = q.answer ? q.answer : @"";
            dict[@"subCount"] = q.has_sub;
            dict[@"qstId"] = q.qstId ? q.qstId : q.docID;
            dict[@"userAnswer"] = (q.userAnswer) ? q.userAnswer : @"";
            dict[@"resultFlag"] = q.right ? @"1" : @"0";
            dict[@"parentId"] = q.parentid ? q.parentid : @"0";
            dict[@"viewTypeId"] = q.qtype ? q.qtype : @"0";
            dict[@"tqId"] = q.tqId ? q.tqId : @"0";
            if (q.scoreMarkedIndex != -1) { //老师评分
                dict[@"userScoreRate"] = q.scores[q.scoreMarkedIndex];
            }
            else{
                dict[@"userScoreRate"] = @"";
            }
            dict[@"userAnswerImage"] = @"";
            [answers addObject:dict];
            
            // 计算分数
            if (q.right) {
                paper.gotScore += [q.score integerValue];
                paper.rightCount += 1;
            }
            else{
                paper.wrongCount += 1;
            }
        }
    }
//    NSLog(@"answers: %@",answers);
    return answers;
}

#pragma mark 收藏新接口
// 收藏
-(void)collectPaperNewWithQuestion: (PaperQuestion*)question
                     paperParam: (PaperParam*)param
                        succeed: (PaperRequestSucceedBlock)succeedBlock
                         failed: (PaperRequestFailedBlock)failedBlock{
    NSString *url = [NSString stringWithFormat:@"%@/collectTopicNoZip",[self collectBaseUrl]];
    NSDictionary *paramDict = @{
        @"userId": param.userId,
        @"loginName": param.loginName,
        @"paperId": param.paperId,
        @"paperName": param.paperName,
        @"topicId": question.qstId,//question.qstId,
        @"topicName": @"",
        @"subjectId": param.subjectId,
                                @"subjectName": param.subjectName,
    };
    NSLog(@"collect url: %@ \n param: %@",url,paramDict);
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //!!! 不加这个会报错：unacceptable content-type: text/plain
    manager.responseSerializer.acceptableContentTypes = nil;
    [manager POST:url parameters:paramDict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        /*
         {"status":"1","msg":"收藏成功","id":27}
         */
        NSLog(@"%@ %@", task, responseObject);
        if ([responseObject[@"status"] boolValue]) {
            succeedBlock();
        }
        else{
            failedBlock([NSError errorWithDomain:@"收藏失败" code:404 userInfo:nil]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (error) {
            NSLog(@"failed: %@",error.localizedDescription);
            failedBlock(error);
        }
    }];
}

// 取消收藏
-(void)cancelCollectPaperNewWithQuestion: (PaperQuestion*)question
                           paperParam: (PaperParam*)param
                              succeed: (PaperRequestSucceedBlock)succeedBlock
                               failed: (PaperRequestFailedBlock)failedBlock{
    NSString *url = [NSString stringWithFormat:@"%@/uncollectTopic",[self collectBaseUrl]];
    NSDictionary *paramDict = @{
        @"userId": param.userId,
        @"paperId": param.paperId,
        @"topicId": question.qstId,
    };
    NSLog(@"uncollect url: %@ \n param: %@",url,paramDict);
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //!!! 不加这个会报错：unacceptable content-type: text/plain
    manager.responseSerializer.acceptableContentTypes = nil;
    [manager POST:url parameters:paramDict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSLog(@"%@ %@", task, responseObject);
        /*
         {"status":"1","msg":"取消收藏成功"}
         */
        if ([responseObject[@"status"] boolValue]) {
            succeedBlock();
        }
        else{
            failedBlock([NSError errorWithDomain:@"取消收藏失败" code:404 userInfo:nil]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (error) {
            NSLog(@"failed: %@",error.localizedDescription);
            failedBlock(error);
        }
    }];
}

// 获取收藏试题列表
-(void)getCollectedPaperQuestionsNewWithPaperParam: (PaperParam*)param
                                        succeed: (GetCollectedQuestionsSucceedBlock)succeedBlock
                                         failed: (PaperRequestFailedBlock)failedBlock{
    NSString *url = [NSString stringWithFormat:@"%@/getAllCollectedTopics",[self collectBaseUrl]];
    NSDictionary *paramDict = @{
        @"userId": param.userId
    };
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = nil;
    [manager POST:url parameters:paramDict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        NSLog(@"%@ %@", task, responseObject);
        if ([responseObject[@"status"] boolValue]) {
            NSArray *data = responseObject[@"data"];
            NSMutableArray *array = [NSMutableArray array];
            for (NSDictionary *dict in data) {
                [array addObject:[PaperCollect collectWithDictionary:dict]];
            }
            succeedBlock(array);
        }
        else{
            failedBlock([NSError errorWithDomain:@"加载收藏试题失败" code:404 userInfo:nil]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (error) {
            NSLog(@"failed: %@",error.localizedDescription);
            failedBlock(error);
        }
    }];
}

#pragma mark 试题收藏相关

// 加入收藏
/*
 userId
 用户id
 loginName
 用户名
 paperId
 试卷id
 paperName
 试卷名称
 topicId
 试题id
 topicName
 试题内容
 subjectId
 学科id
 subjectName
 学科名称
 zipFile
 */
-(void)collectPaperWithQuestion: (PaperQuestion*)question
                    paperParam: (PaperParam*)param
                        succeed: (PaperRequestSucceedBlock)succeedBlock
                         failed: (PaperRequestFailedBlock)failedBlock{
    NSString *url = [NSString stringWithFormat:@"%@/collectTopic",[self collectBaseUrl]];
    NSString *zipPath = [self zipPathOfCollectQuestion:question paperId: param.paperId];
    if (!zipPath) {
        NSLog(@"收藏试题zip包生成失败");
        failedBlock([NSError errorWithDomain:@"收藏失败" code:404 userInfo:nil]);
        return;
    }
    NSDictionary *paramDict = @{
       @"userId": param.userId,
       @"loginName": param.loginName,
       @"paperId": param.paperId,
       @"paperName": param.paperName,
       @"subjectId": param.subjectId,
       @"subjectName": param.subjectName,
       @"topicId": param.paperId,//question.qstId,
       @"topicName": @"",
       @"zipFile": zipPath
    };
    NSLog(@"collect url: %@ \n param: %@",url,paramDict);

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //!!! 不加这个会报错：unacceptable content-type: text/plain
    manager.responseSerializer.acceptableContentTypes = nil;
    [manager POST:url parameters:paramDict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        /*
         {"status":"1","msg":"收藏成功","id":27}
         */
        NSLog(@"%@ %@", task, responseObject);
        if ([responseObject[@"status"] boolValue]) {
            // 删除zip
            if ([self removeDirectoryAtPath:zipPath]){
                succeedBlock();
            }
        }
        else{
            failedBlock([NSError errorWithDomain:@"收藏失败" code:404 userInfo:nil]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (error) {
            NSLog(@"failed: %@",error.localizedDescription);
            failedBlock(error);
        }
    }];
}

// 收藏试题的zip路径
-(NSString*)zipPathOfCollectQuestion: (PaperQuestion*)question
                             paperId: (NSString*)paperId{
    // 从question 生成jsonStr
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:[question dictionary]];
    // 增加一些辅助信息
    
    
    
    
    NSString *jsonStr = [self jsonStringFromJsonObject:[question dictionary]];
    // 保存成question.json
    NSString *jsonPath = [self collectedQuestionJsonPathWithId:paperId];
    NSString *zipPath = [self collectedQuestionZipPathWithId:paperId];
    NSData *data = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
    
    // 查找试题中用到的图片
    NSMutableArray *paths = [self imagePathsUsedOfQuestion:question paperId:paperId];
    [paths addObject:jsonPath];
    
    BOOL writed = [data writeToFile:jsonPath  atomically:true];
    BOOL ziped = [SSZipArchive createZipFileAtPath:zipPath withFilesAtPaths:paths];
    if (writed && ziped) {
        // zip
        NSLog(@"collect question json: %@ \n zip: %@",jsonPath,zipPath);
        // 删除json
        [self removeDirectoryAtPath:jsonPath];
        return zipPath;
    }
    return nil;
}

// 图片路径
-(NSMutableArray*)imagePathsUsedOfQuestion: (PaperQuestion*)question paperId: (NSString*)paperId{
    NSString *imagePath = [self paperImagesPathWithId:paperId];
    NSMutableArray *arr = [NSMutableArray new];
    for (NSString *file in [[NSFileManager defaultManager] subpathsAtPath:imagePath]) {
        if ([question.questionContent containsString:file]) {
            [arr addObject:[NSString stringWithFormat:@"%@%@",imagePath,file]];
        }
    }
    return arr;
}

// 取消收藏
/*
 userId
 用户id
 loginName
 用户名
 topicId
 */
-(void)cancelCollectPaperWithQuestion: (PaperQuestion*)question
                           paperParam: (PaperParam*)param
                              succeed: (PaperRequestSucceedBlock)succeedBlock
                               failed: (PaperRequestFailedBlock)failedBlock{
    NSString *url = [NSString stringWithFormat:@"%@/uncollectTopic",[self collectBaseUrl]];
    NSDictionary *paramDict = @{
            @"userId": param.userId,
            @"loginName": param.loginName,
            @"topicId": question.qstId,
    };
    NSLog(@"uncollect url: %@ \n param: %@",url,paramDict);

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //!!! 不加这个会报错：unacceptable content-type: text/plain
    manager.responseSerializer.acceptableContentTypes = nil;
    [manager POST:url parameters:paramDict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        NSLog(@"%@ %@", task, responseObject);
        /*
         {"status":"1","msg":"取消收藏成功"}
         */
        if ([responseObject[@"status"] boolValue]) {
            succeedBlock();
        }
        else{
            failedBlock([NSError errorWithDomain:@"取消收藏失败" code:404 userInfo:nil]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (error) {
            NSLog(@"failed: %@",error.localizedDescription);
            failedBlock(error);
        }
    }];
}

// 提交分数到云平台
/*
 userId
 用户id
 loginName
 用户名
 paperId
 试卷id
 paperName
 试卷名称
 subjectId
 学科id
 subjectName
 学科名称
 score
 */
-(void)savePaperScoreToServerWithPaper: (PaperModel*)paper
                              paperParam: (PaperParam*)param
                                 succeed: (PaperRequestSucceedBlock)succeedBlock
                                  failed: (PaperRequestFailedBlock)failedBlock{
    NSString *url = [NSString stringWithFormat:@"%@/savePaperScore",[self collectBaseUrl]];
    NSDictionary *paramDict = @{
                                @"userId": param.userId,
                                @"loginName": param.loginName,
                                @"paperId": param.paperId,
                                @"paperName": param.paperName,
                                @"subjectId": param.subjectId,
                                @"subjectName": param.subjectName,
                                @"score": @(paper.gotScore)
    };
    NSLog(@"save paper url: %@ param: %@",url,paramDict);
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //!!! 不加这个会报错：unacceptable content-type: text/plain
    manager.responseSerializer.acceptableContentTypes = nil;
    [manager POST:url parameters:paramDict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        /*
         {"status":"1","msg":"添加成功"}
         */
        NSLog(@"%@ %@", task, responseObject);
        if ([responseObject[@"status"] boolValue]) {
            succeedBlock();
        }
        else{
            failedBlock([NSError errorWithDomain:@"保存分数失败" code:404 userInfo:nil]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (error) {
            NSLog(@"failed: %@",error.localizedDescription);
            failedBlock(error);
        }
    }];
}

// 收藏的试题列表
/*
 userId
 用户id
 loginName
 */
-(void)getCollectedPaperQuestionsWithPaperParam: (PaperParam*)param
                                        succeed: (DownloadCollectedQuestionSucceedBlock)succeedBlock
                                         failed: (PaperRequestFailedBlock)failedBlock{
    NSString *url = [NSString stringWithFormat:@"%@/getcollectTopics",[self collectBaseUrl]];
    NSDictionary *paramDict = @{
        @"userId": param.userId,
        @"loginName": param.loginName,
    };
    
    __weak __typeof(self) weakSelf = self;
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //!!! 不加这个会报错：unacceptable content-type: text/plain
    manager.responseSerializer.acceptableContentTypes = nil;
    [manager POST:url parameters:paramDict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        /*
         {"status":"1","msg":"添加成功"}
         
         {"status":"0","msg":"请先收藏题目"}
         */
        NSLog(@"%@ %@", task, responseObject);
        if ([responseObject[@"status"] boolValue]) {
            // 下载zip
            NSString *url = responseObject[@"msg"];
            [weakSelf downloadCollectedQuestionsZipWithUrl:url succeed:succeedBlock failed:failedBlock];
        }
        else{
            failedBlock([NSError errorWithDomain:@"加载收藏试题失败" code:404 userInfo:nil]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (error) {
            NSLog(@"failed: %@",error.localizedDescription);
            failedBlock(error);
        }
    }];
}

// 下载收藏试题zip
-(void)downloadCollectedQuestionsZipWithUrl: (NSString*)url
                                    succeed: (DownloadCollectedQuestionSucceedBlock)succeedBlock
                                     failed: (PaperRequestFailedBlock)failedBlock{
    NSLog(@"download paper url: %@",url);
    NSURL *URL = [NSURL URLWithString: url];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    __weak __typeof(self) weakSelf = self;
    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        NSURL *path = [NSURL fileURLWithPath: zipsPath];
        return [path URLByAppendingPathComponent:[response suggestedFilename]];
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
        if (error) {
            failedBlock(error);
        }
        else{
            NSLog(@"%@ %@", response, filePath);
            [weakSelf unzipAndParseZipFileAtPath:filePath.path succeed:succeedBlock failed:failedBlock];
        }
    }];
    [downloadTask resume];
}

#pragma mark - 收藏试题下载、解析
-(void)unzipAndParseZipFileAtPath: (NSString*)path
                      succeed: (DownloadCollectedQuestionSucceedBlock)succeedBlock
                       failed: (PaperRequestFailedBlock)failedBlock{
    
}


#pragma mark tool method
// 试卷下载 - 提交 url
-(NSString*)paperBaseUrl{
    NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Config.plist" ofType:nil]];
    return dict[@"paper_baseUrl"];
}

// 试卷收藏 - 取消收藏 - 收藏列表 url
-(NSString*)collectBaseUrl{
    NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Config.plist" ofType:nil]];
    return dict[@"collect_baseUrl"];
}

// 文件是否存在
-(BOOL)fileExists: (NSString*)path{
    BOOL isDirectory;
    NSFileManager *m = [NSFileManager defaultManager];
    return [m fileExistsAtPath:path isDirectory:&isDirectory];
}

// 重命名/文件移动
-(void)moveFilesAtDirectory: (NSString*)dirPath toPath: (NSString*)toPath{
    NSString *newPath = nil;
    NSError *error = nil;
    NSFileManager *fm = [NSFileManager defaultManager];
    if ([self fileExists: dirPath]) {
        for (NSString *sub in [fm contentsOfDirectoryAtPath:dirPath error: &error]) {
            newPath = [toPath stringByAppendingString:sub];
            [self moveFileAtPath: [dirPath stringByAppendingString: sub] toPath: newPath];
        }
        if (error) {
            NSLog(@"moveFilesAtDirectory error: %@",error.localizedDescription);
            return;
        }
    }
    NSLog(@"all files moved to: %@", toPath);
}

-(void)moveFileAtPath: (NSString*)path
                   toPath: (NSString*)toPath{
    NSError *error;
    NSFileManager *m = [NSFileManager defaultManager];
    if ([self fileExists:path]) {
        [self removeDirectoryAtPath:toPath]; // 移除已有的
        
        [m moveItemAtPath: path toPath:toPath error:&error];
        if (error) {
            NSLog(@"moveFileAtPath error: %@",error.localizedDescription);
            return;
        }
        return;
    }
    NSLog(@"moveFileAtPath: file is not exists %@",path);
}

-(NSString *)jsonStringFromJsonObject:(id)object{
    NSError *error;
    if ([NSJSONSerialization isValidJSONObject:object]) {
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object options:NSJSONWritingPrettyPrinted error:&error];
        NSString *json =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        // 过滤掉 \转义字符
        json = [json stringByReplacingOccurrencesOfString:@"\\" withString:@""];
//        NSLog(@"%@",json);
        
        return json;
    }
    NSLog(@"error------jsonObject is not  Valid!");
    return nil;
}

-(BOOL)createDirectoryAtPath: (NSString*)path{
    NSError *error;
    NSFileManager *m = [NSFileManager defaultManager];
    if (![self fileExists:path]) {
        [m createDirectoryAtPath:path withIntermediateDirectories:true attributes:nil error:&error];
        if (error) {
            NSLog(@"createDirectoryAtPath error: %@",error.localizedDescription);
            return false;
        }
    }
    return true;
}

-(BOOL)removeDirectoryAtPath: (NSString*)path{
    NSError *error;
    NSFileManager *m = [NSFileManager defaultManager];
    if ([self fileExists:path]) {
        [m removeItemAtPath:path error:&error];
        if (error) {
            NSLog(@"removeDirectoryAtPath error: %@",error.localizedDescription);
            return false;
        }
    }
    return true;
}

// 子文件
-(NSMutableArray*)subFilesPathAtDirectory: (NSString*)path{
    NSMutableArray *arr = [NSMutableArray new];
    for (NSString *file in [[NSFileManager defaultManager] subpathsAtPath:path]) {
        [arr addObject:[NSString stringWithFormat:@"%@/%@",path,file]];
    }
    return arr;
}

@end
